package com.lsh.oms.core.proxy.handler;

import com.lsh.oms.core.proxy.AbstractAsyncTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by panxudong on 16/12/27.
 */
public class AsyncTaskHandler {

    private static Logger logger = LoggerFactory.getLogger(AsyncTaskHandler.class);

    private static ExecutorService executor = Executors.newSingleThreadExecutor();

    public static void executeAsyncTask(AbstractAsyncTask asyncTask) {
        executor.submit(new AsyncTaskHandler().new AsyncTask(asyncTask));
    }

    public static void executeAsyncTask(AbstractAsyncTask... asyncTasks) {
        executor.submit(new AsyncTaskHandler().new AsyncTask(asyncTasks));
    }

    public static void executeAsyncTask(List<AbstractAsyncTask> asyncTasks) {
        executor.submit(new AsyncTaskHandler().new AsyncTask(asyncTasks));
    }

    class AsyncTask implements Runnable {
        private List<AbstractAsyncTask> asyncTasks;

        public AsyncTask(AbstractAsyncTask asyncTask) {
            this.asyncTasks = new ArrayList<>();
            this.asyncTasks.add(asyncTask);
        }

        public AsyncTask(AbstractAsyncTask[] asyncTasks) {
            this.asyncTasks = new ArrayList<>();
            for(AbstractAsyncTask asyncTask : asyncTasks) {
                this.asyncTasks.add(asyncTask);
            }
        }

        public AsyncTask(List<AbstractAsyncTask> asyncTasks) {
            this.asyncTasks = asyncTasks;
        }

        @Override
        public void run() {
            logger.info(" [AsyncTask][Async execute task start][Size:" + asyncTasks.size() + "]");
            for(AbstractAsyncTask asyncTask : this.asyncTasks) {
                String msg = " [AsyncTask][Execute " + asyncTask.getAbstractTaskType().getDesc();
                logger.info(msg + " start]");
                try {
                    asyncTask.execute();
                } catch (Exception e) {
                    logger.error(msg + " error]" + "[Error Class : " + e.getClass() + ", Error Message : " + e.getMessage() + "]");
                    logger.error(e.getMessage(), e);
                }
                logger.info(msg + " end]");
            }
            logger.info(" [AsyncTask][Async execute task end]");
        }
    }
}
